package com.om.abom.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.om.abom.entity.AppServerEntity;
import com.om.abom.service.AppServerService;
import com.om.abom.utils.PageResult;
import com.om.abom.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;


@RestController
@RequestMapping("appServer")
@CrossOrigin
@Slf4j
public class AppServerController
{
    @Autowired
    private AppServerService appServerService;

    /**
     * 启动服务
     */
    @PostMapping("/start/{id}")
    public R<Object> start(@PathVariable("id") Long id)
    {
        String errorMsg = appServerService.start(id);

        if (errorMsg != null) {
            return R.error(errorMsg);
        }
        return R.success().message("启动成功");
    }

    /**
     * 停止服务
     */
    @PostMapping("/stop/{id}")
    public R<Object> stop(@PathVariable("id") Long id)
    {
        String errorMsg = appServerService.stop(id);

        if (errorMsg != null) {
            return R.error(errorMsg);
        }
        return R.success().message("停止成功");
    }

    /**
     * 分页
     */
    @GetMapping("/page")
    public R<PageResult<AppServerEntity>> page(@RequestParam(defaultValue = "1") int page,
                                               @RequestParam(defaultValue = "10") int pageSize,
                                               @RequestParam(required = false) String serverName)
    {
        Page<AppServerEntity> pageInfo = new Page<>(page, pageSize);

        LambdaQueryWrapper<AppServerEntity> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.like(StringUtils.isNotEmpty(serverName), AppServerEntity::getServerName, serverName);

        queryWrapper.orderByDesc(AppServerEntity::getUpdateTime);

        appServerService.page(pageInfo, queryWrapper);

        return R.success(new PageResult<>(pageInfo));
    }


    /**
     * 信息
     */
    @GetMapping("/{id}")
    public R<AppServerEntity> get(@PathVariable("id") Long id)
    {
        AppServerEntity appServer = appServerService.getById(id);

        return R.success(appServer);
    }

    /**
     * 新增
     */
    @PostMapping
    public R<Null> add(@RequestBody AppServerEntity appServer)
    {
        appServerService.save(appServer);

        return R.success();
    }

    /**
     * 修改
     */
    @PutMapping
    public R<Null> update(@RequestBody AppServerEntity appServer)
    {
        appServerService.updateById(appServer);

        return R.success();
    }

    /**
     * 删除
     */
    @DeleteMapping
    public R<Null> delete(@RequestBody Long[] ids)
    {
        appServerService.removeByIds(Arrays.asList(ids));

        return R.success();
    }
}

